/**
 * 封装uni-app的的request
 */
const http = {}

/**
 * 异步请求
 */
http.ajax = function({
	url = "",
	data = {},
	method = "GET",
	showLoad = false,
	showMsg = false
}){
  return new Promise(function (resolve, reject) {
	showLoad?uni.showLoading({title:'loading'}):console.log("loading...");
    uni.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json;charset=utf-8',
		'token': uni.getStorageSync('token')?uni.getStorageSync('token'):"false"
      },
      success: function (res) {
		uni.hideLoading();
		if (res.statusCode == 200) {
			showMsg?uni.showToast({title:res.data.msg,icon:"none"}):console.log(res.data.msg);
			if (res.data && res.data.code == 401) {// 401, token失效
				var token = '';
				uni.setStorageSync('token', token);
				//需要登录后才可以操作
				uni.showModal({
					title: '请先登录',
					content: '当前操作需要登录',
					success: function (res) {
						if (res.confirm) {
							uni.navigateTo({url:"/pages/login/login"});
						}
					}
				});
			} else {
				resolve(res.data);
			}
		} else {
			reject(res);
		}
      },
      fail: function (err) {
		uni.hideLoading();
		console.log('err',err);
		showMsg?uni.showToast({title:err.errMsg,icon:"none"}):console.log("err",err.errMsg);
		reject(err.errMsg)
      }
    })
  });
}

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName) => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  var devUrl = 'http://192.168.0.104:8099/renren-fast/app/';
  var proUrl = 'https://yixiaoguoji.qianduyiren.cn/platform-framework/api/';
  return (process.env.NODE_ENV === 'production'?devUrl:devUrl) + actionName
}

/**
 * 获取指定的URL参数值 
 * url: http://www.quwan.com/index?name=tyler
 * 返回值:params 
 */
http.getParam = function (url) {
	var params = {};
	url =decodeURI(decodeURI(url));
	if(url && url.indexOf("?")!=-1){
		var urlArray = url.split("?");
		if(urlArray.length==2){
			var paramArray = urlArray[1].split("&");
			if(paramArray.length>=1){
				for(var i in paramArray){
					var param = paramArray[i].split("=");
					params[param[0]]=param[1]
				}
			}
		}
	}
	return params;
}
	
/** 
 * 设置请求的URL参数值 
 * 返回值:url 
 */
http.addUrlParam = function (url = '', params = {}) {
	if(url && JSON.stringify(params)!="{}"){
	    var paramArray = [];
	    mui.each(params,function(index,item){
	      	var param = index+'='+item
	      	paramArray.push(param)
	    })
		var url2=encodeURI(url+'?'+paramArray.join('&'));
		var enurl = encodeURI(url2);
	    return enurl
	}else{
		return url;
	}
}

export default http